import { useState, useEffect, forwardRef } from "react";
import { Button, Popconfirm, Modal, Input, message } from "antd";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import { CommonModal } from "@/views/components/CommonModal";
import { getDelimiterConfig, delimiterConfigDelete, delimiterConfigSave } from "../service";
import { cloneDeep, set } from "lodash";

const CombAnalyticFormula = forwardRef(({ title, onCancel }) => {
	const [rowKeys, setRowKeys] = useState([]);
	const [list, setList] = useState([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	const [selectedRows, setSelectedRows] = useState([]);

	const goodsList = [
		{
			skuName: "+",
			skuCode: "A+B",
			skuCode2: "A+B=A*1+B*1",
			skuCode3: "A和B为系统商品编码；1为组合包含单品的数量"
		},
		{
			skuName: "-",
			skuCode: "A=2-B",
			skuCode2: "A2-B=A*2+B*1",
			skuCode3: "A和B为系统商品编码；1、2为组合包含单品的数量"
		},
		{
			skuName: "&",
			skuCode: "A=2&B=3",
			skuCode2: "A2&B3=A*2+B*3",
			skuCode3: "A和B为系统商品编码；2、3为组合包含单品的数量"
		}
	];
	const columns1 = [
		{
			title: "商品分隔符",
			dataIndex: "skuName"
		},
		{
			title: "组合装编码",
			dataIndex: "skuCode"
		},
		{
			title: "组合装解析公式",
			dataIndex: "skuCode2"
		},
		{
			title: "说明",
			dataIndex: "skuCode3"
		}
	];
	const columns = [
		{
			title: "序号",
			dataIndex: "index",
			lock: true,
			render: (t, r, i) => {
				return i + 1;
			},
			width: 100
		},
		{
			title: "商品分隔符",
			dataIndex: "splitter",
			width: 100,
			render: (t, r, i) => {
				console.log(r, "ssssssssssss");
				// if (t) return <span>{t}</span>;
				if (r.isShow == true)
					return (
						<div>
							<Input style={{ border: "1px solid red" }} defaultValue={t} onBlur={e => handleChange(e.target.value, r, i)} />
						</div>
					);

				return <Input defaultValue={t} onBlur={e => handleChange(e.target.value, r, i)} />;
			}
		}
	];

	useEffect(() => {
		getDelimiterConfigList();
	}, []);

	const deleteFn = () => {
		if (selectedRowKeys.length === 0) {
			return message.error("请先选择数据");
		}
		const delimiters = selectedRows.map(item => item.splitter)?.join(",");
		if (selectedRows) {
			Modal.info({
				title: "提示",
				content: <div style={{ marginTop: 24, marginLeft: 45 }}>确定要删除分隔符"{delimiters}"吗？</div>,
				centered: true,
				okText: "确认",
				cancelText: "取消",
				onOk() {
					delimiterConfigDelFn();
					setSelectedRows([]);
					setSelectedRowKeys([]);
				}
			});
		}
	};

	const addFn = () => {
		let list1 = [{ id: "", splitter: "" }];
		setList([...list, ...list1]);
	};
	const delimiterConfigDelFn = async () => {
		const { success } = await delimiterConfigDelete(selectedRowKeys);
		if (success) {
			message.success("操作成功");
			getDelimiterConfigList();
		}
	};
	const handleChange = async (e, record, index) => {
		console.log(index, "index");
		let arr = cloneDeep(list);
		arr?.map((x, i) => {
			console.log(i, "sss");
			if (index == i) {
				x.splitter = e;
				return;
			}
		});
		let splitterCount = {};
		arr.forEach(item => {
			if (splitterCount[item.splitter]) {
				splitterCount[item.splitter]++;
			} else {
				splitterCount[item.splitter] = 1;
			}
		});

		// 步骤2: 遍历数组，添加isShow字段
		arr.forEach(item => {
			if (splitterCount[item.splitter] > 1) {
				item.isShow = true;
			} else {
				item.isShow = false;
			}
		});
		console.log(arr, "arr");
		setList(arr);
	};
	function hasDuplicateSplitter(arr) {
		const splitterSet = new Set();
		for (const obj of arr) {
			if (splitterSet.has(obj.splitter)) {
				return true; // 找到了重复的splitter
			}
			splitterSet.add(obj.splitter); // 添加当前splitter到集合中
		}
		return false; // 没有找到重复的splitter
	}
	const onOk = () => {
		if (hasDuplicateSplitter(list)) {
			message.error("分隔符重复");
		} else {
			const promises = list?.map(async item => {
				const { data, success } = await delimiterConfigSave(item);
				return data.records;
			});
			Promise.all(promises)
				.then(results => {
					message.success("操作成功");
					onCancel();
				})
				.catch(error => {
					console.error("Error fetching data:", error);
				});
		}
	};
	const getDelimiterConfigList = async () => {
		const { data, success } = await getDelimiterConfig();
		if (success) {
			setList(data);
		}
	};
	return (
		<CommonModal
			className="views-table-dialog"
			title={{ title }}
			visible={true}
			width="1400px"
			onOk={onOk}
			onCancel={onCancel}
			// footer={
			// 	<Button size="middle" onClick={onCancel}>
			// 		取消
			// 	</Button>
			// }
		>
			<div>温馨提示</div>
			<div>
				1）请避免商品分隔符与您的系统商品生成规则中的连接符相同；商品编码中仅存在一个分隔符时将会被判定为组合装，自动生成组合装编号而不是系统商品编码
			</div>
			<div>
				2）设置店铺商品编码对应组合装时，可按照设置的分隔符来生成公式解析商品，并自动生成系统组合装商品。（请在三方店铺填写组合子商品编码时，输入erp系统商品编码）
			</div>
			<div>
				3）填写商品编码时，根据您自定义的商品分隔符来区分不同的商品，在子商品后用“=”加上“正整数”来表示单品的数量，≤0或不填都默认为1件。以下为示例：
			</div>
			<CommonTable
				rowKey="key"
				style={{ width: 1000 }}
				scroll={{ y: `calc(100vh - 250px)` }}
				columns={columns1}
				dataSource={goodsList}
				pagination={false}
			/>
			<div className="flex mt20 mb20">
				<Button type="primary" style={{ marginRight: "8px", width: 80, height: 30 }} onClick={addFn}>
					新增
				</Button>
				<Button style={{ marginRight: "8px", width: 80, height: 30 }} onClick={deleteFn}>
					删除
				</Button>
			</div>
			<div className="views-container">
				<CommonTable
					scroll={{ y: `calc(100vh - 250px)` }}
					style={{ width: 500 }}
					columns={columns}
					rowSelection={{
						selectedRowKeys,
						onChange: (selectedRowKeys, selectedRows) => {
							setSelectedRowKeys(selectedRowKeys);
							setSelectedRows(selectedRows);
						}
					}}
					rowKey="id"
					dataSource={list}
					pagination={false}
				/>
			</div>
		</CommonModal>
	);
});

export default CombAnalyticFormula;
